<template>
  <div class="tpl-box">
    <div class="button-box">
      <div style="display: flex;">
        <ac-input v-model="filterName" style="width: 150px" placeholder="模板名称" />
        <ac-remote-select
          v-model="category"
          data-url="/system/visualTemplate/queryCategoryPage"
          style="margin-left: 10px;width: 150px"
          placeholder="所属分类"
        />
        <el-button style="margin-left: 10px;" type="primary" @click="loadTplData">
          <cc-icon iconId="018dc9c3efe489a7d117" style="margin-right: 5px" />查询
        </el-button>
        <el-button style="margin-left: 10px;" type="success" @click="addTpl">
          <cc-icon iconId="018dc9c3efed46e8b927" style="margin-right: 5px" />新增
        </el-button>
        <div @click="selectMode = !selectMode" style="margin-left: 20px;cursor: pointer">
          <el-checkbox v-model="selectMode" />
          <span style="margin-left: 5px">选择模式</span>
        </div>
        <el-button v-if="selectMode" style="margin-left: 10px;" type="primary" @click="selectAll">
          <cc-icon iconId="018dca412c4e207388f7" style="margin-right: 5px" />全选
        </el-button>
        <el-button v-if="selectMode" style="margin-left: 10px;" type="primary" @click="unselectAll">
          <cc-icon iconId="018dca412c4ebd53fd1d" style="margin-right: 5px" />取消选择
        </el-button>
      </div>
      <div class="button-item">
        <el-upload
          action=""
          :http-request="handleImport"
          :show-file-list="false"
          accept=".dat"
        >
          <el-button
            style="
              color: #ffffff;
              background-color: #00CED1;
              border: 1px solid #00CED1;
            "
          >
            <ac-icon
              iconId="018dcc257a83b0d6deab"
              title="导入模板"
              style="margin-right: 8px"
            />导入模板
          </el-button>
        </el-upload>

        <el-button
          style="
            color: #ffffff;
            background-color: #FF8C00;
            border: 1px solid #FF8C00
          "
          @click="downloadTpl()"
        >
          <ac-icon
            iconId="018dcc257a840e260284"
            title="导出模板"
            style="margin-right: 8px"
          />导出模板
        </el-button>
      </div>
    </div>

    <div
      v-for="item in tplList"
      :key="item.id"
      :class="['item-box', selectMode && item.checked ? 'active' : '']"
      @click="clickItem(item)"
    >
      <div class="item-main">
        <div class="item-body" :style="{backgroundImage: 'url(' + imageUrl + item.imageId + ')'}" />
        <div class="footer">
          <div class="item-name">{{item.name}}</div>
          <div class="item-button">
            <el-tooltip
              effect="light"
              content="预览"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="15"
                iconId="018dc9c3efed3042d4d3"
                color="#909399"
                @click.stop="previewTpl(item)"
              />
            </el-tooltip>
            <el-tooltip
              effect="light"
              color="#909399"
              content="应用"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="15"
                iconId="018ece4f71ce2133be96"
                color="#67C23A"
                @click.stop="useTpl(item)"
              />
            </el-tooltip>
            <el-tooltip
              effect="light"
              content="编辑"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="16"
                color="#0085f6"
                iconId="018ece4f6918a49a759b"
                @click.stop="editTpl(item)"
              />
            </el-tooltip>
            <el-tooltip
              effect="light"
              content="设计"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="15"
                iconId="018dca6db20c6a3aaf68"
                color="#0085f6"
                @click.stop="designTpl(item)"
              />
            </el-tooltip>
            <el-tooltip
              effect="light"
              content="删除"
              popper-class="padding-10-15"
            >
              <ac-icon
                size="15"
                iconId="018dc9c3efd3a0502886"
                color="#F56C6C"
                @click.stop="deleteTpl(item)"
              />
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
  </div>

  <el-dialog
    v-model="useVisible"
    :title="useTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="useForm"
      label-width="100px"
      label-position="right"
      :model="useData"
      :rules="useRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="页面名称" prop="name">
            <el-input v-model="useData.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="页面目录" prop="folderId">
            <ac-tree
              v-model="useData.folderId"
              data-url="/system/pageFolder/queryTree"
              :leafSelect="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="useVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="useLoading"
        @click="submitUseForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <el-dialog
    v-model="tplVisible"
    :title="tplTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="tplForm"
      label-width="100px"
      label-position="right"
      :model="tplData"
      :rules="tplRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="tplData.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="所属分类" prop="category">
            <ac-remote-select
              v-model="tplData.category"
              data-url="/system/visualTemplate/queryCategoryPage"
              allowCreate
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="tplVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="tplLoading"
        @click="submitTplForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--页面设计-->
  <el-dialog
    v-model="editorVisible"
    class="no-padding no-header no-scroll"
    :show-header="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <TplEditor
      ref="tplEditor"
      v-bind="editorOptions"
      @quit="designQuit"
    />
  </el-dialog>

  <!--页面预览-->
  <el-dialog
    v-model="previewVisible"
    class="no-padding no-header no-scroll"
    :show-header="false"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <div class="preview-box">
      <img :src="previewImg"  alt=""/>
    </div>
  </el-dialog>

  <!--页面编辑-->
  <el-dialog
    v-model="pageVisible"
    class="no-padding"
    :title="pageTitle"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <PageEdit ref="page" :options="pageData" @afterSubmit="afterPageSubmit"/>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="pageVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="pageLoading"
        @click="submitPageForm"
      >提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from "@/http/api";
import { ElMessage, ElMessageBox } from "element-plus";
import tool from "@/utils/tool";
import TplEditor from "../dashboard/editor.vue";
import PageEdit from "@/admin/codeless/pageEdit.vue";

const imageUrl = ref(import.meta.env.VITE_IMAGE_PATH);
const selectMode = ref(false);
const filterName = ref('');
const category = ref('');
const tplList = ref([]);
const tplVisible = ref(false);
const tplTitle = ref('');
const tplForm = ref();
const tplData = ref({});
const tplLoading = ref(false);
const tplRules = ref({
  name: [
    {required: true, message: '名称不能为空！', trigger: 'blur'},
    {max: 50, message: '名称长度最多只能是50个字符', trigger: ['blur', 'change']}
  ],
  title: [
    {required: true, message: '标题不能为空！', trigger: 'blur'},
    {max: 50, message: '标题长度最多只能是50个字符', trigger: ['blur', 'change']}
  ],
  remark: [
    {max: 4000, message: '备注长度最多只能是4000个字符', trigger: ['blur', 'change']}
  ],
});

const useVisible = ref(false);
const useTitle = ref('');
const useForm = ref();
const useData = ref({});
const useLoading = ref(false);
const useRules = ref({
  name: [
    {required: true, message: '页面名称不能为空！', trigger: 'blur'},
    {max: 50, message: '名称长度最多只能是50个字符', trigger: ['blur', 'change']}
  ],
  folderId: [
    {required: true, message: '页面目录不能为空！', trigger: 'blur'},
  ],
});

const editorVisible = ref(false);
const editorOptions = ref({});
const tplEditor = ref();
const previewVisible = ref(false);
const previewImg = ref('');

const pageVisible = ref(false);
const pageTitle = ref('');
const pageData = ref({});
const pageLoading = ref();
const page = ref();

const addTpl = () => {
  tplData.value = {};
  tplTitle.value = "新增模板";
  tplLoading.value = false;
  tplVisible.value = true;
};

const clickItem = item => {
  if (selectMode.value) {
    item.checked = !item.checked;
  } else {
    designTpl(item);
  }
};

const useTpl = async(item) => {
  if (!item) return;

  const res = await api.post('/system/visualTemplate/queryBy', {id: item.id});
  useData.value = {
    "type": "可视化",
    "layoutMode": "大屏",
    "compList": [
      {
        "name": "页面",
        "type": "可视化",
        "showComp": "1",
        "buttonWrap": "0",
        "visualJson": res.data.jsonText
      }
    ]
  };
  useTitle.value = "应用模板";
  useLoading.value = false;
  useVisible.value = true;
};

const submitUseForm = () => {
  useForm.value.validate(valid => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        useLoading.value = true;
        api.post('/system/page/save', useData.value).then(res => {
          if(res.code === '1') {
            useVisible.value = false;
            ElMessage.success(res.message);
            showPageEdit(res.data.id);
          } else {
            ElMessage.error(res.message);
          }
          useLoading.value = false;
        }).catch(() => {
          useLoading.value = false;
        });
      });
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};

const editTpl = (item) => {
  if (!item) return;

  tplData.value = tool.deepClone(item);
  tplTitle.value = "编辑模板";
  tplLoading.value = false;
  tplVisible.value = true;
};

const submitTplForm = () => {
  tplForm.value.validate(valid => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        tplLoading.value = true;
        api.post('/system/visualTemplate/saveSimple', tplData.value).then(res => {
          if(res.code === '1') {
            tplVisible.value = false;
            ElMessage.success(res.message);
            loadTplData();
          } else {
            ElMessage.error(res.message);
          }
          tplLoading.value = false;
        }).catch(() => {
          tplLoading.value = false;
        })
      });
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};

const hasShow = ref(false);
const previewTpl = (tpl) => {
  previewImg.value = imageUrl.value + tpl.imageId;
  previewVisible.value = true;

  if (hasShow.value) return;
  hasShow.value = true;
  ElMessage.info({
    message: "按【Esc】退出预览。",
    showClose: true,
    duration: 0
  });
};

const downloadTpl = () => {
  const ids = tplList.value.filter(item => item.checked).map(item => item.id);
  if (!ids || ids.length === 0) {
    ElMessage.error("请先选择要导出的模板！");
    return;
  }
  api.downloadFile('/system/visualTemplate/exportData', {ids: ids}).then(res => api.saveFileLocal(res));
};

const deleteTpl = (tpl) => {
  ElMessageBox.confirm('请确认是否删除模板【' + tpl.name + '】？', '提示', {type: 'warning'}).then(() => {
    api.post('/system/visualTemplate/delete', tpl).then(res => {
      if(res.code === '1') {
        ElMessage.success(res.message);
        loadTplData();
      } else {
        ElMessage.error(res.message);
      }
    });
  });
};

const handleImport = (file) => {
  api.uploadFile('/system/visualTemplate/importData', {'file': file.file}).then((res) => {
    ElMessage.success(res.message);
    loadTplData();
  });
};

const designTpl = (tpl) => {
  editorOptions.value.tplId = tpl.id;
  editorOptions.value.saveType = '模板';
  editorVisible.value = true;
};

const designQuit = (reload) => {
  editorVisible.value = false;
  if (reload) {
    loadTplData();
  }
};

const showPageEdit = (id) => {
  pageData.value = {id: id, showEdit: true};
  pageTitle.value = "编辑页面";
  pageVisible.value = true;
};

const submitPageForm = () => {
  page.value.submitData();
};

const afterPageSubmit = () => {
  pageVisible.value = false;
};

const loadTplData = () => {
  tplList.value = [];
  const data = {name: filterName.value, category: category.value};
  api.post('/system/visualTemplate/queryList', data).then(res => {
    tplList.value = res.data || [];
  });
};

const selectAll = () => {
  tplList.value.forEach(data => data.checked = true);
};

const unselectAll = () => {
  tplList.value.forEach(data => data.checked = false);
};

onMounted(() => {
  loadTplData();
});
</script>

<style scoped lang="scss">
.tpl-box {
  padding: 20px;
  height: calc(100% - 40px);
  background: #f5f5f5;
  display: grid;
  grid-template-columns: repeat(auto-fill, 308px);
  grid-gap: 15px;
  justify-content: center;
  align-content: flex-start;
  overflow: auto;
  .button-box {
    display: flex;
    width: 100%;
    grid-column: 1 / -1;
    text-align: right;
    .button-item {
      flex-grow: 1;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      gap: 15px;
      margin-bottom: 20px;
    }
  }
  .item-box {
    cursor: pointer;
    border: 1px solid transparent;
    width: 308px;
    background: #ffffff;
    border-radius: 3px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-content: center;
    .item-main {
      width: 100%;
      padding: 10px 10px 0 10px;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      .item-body {
        width: 288px;
        height: 162px;
        border-radius: 3px;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center center;
      }
      .footer {
        display: flex;
        flex-direction: row;
        .item-name {
          flex-grow: 1;
          height: 40px;
          line-height: 40px;
          overflow: hidden;
          white-space: nowrap;
          word-break: break-all;
          text-overflow: ellipsis;
        }
        .item-button {
          height: 40px;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-end;
          .time-box {
            flex-grow: 1;
            color: #999;
          }

          .ac-icon {
            cursor: pointer;
            margin-left: 12px;
          }
        }
      }
    }
  }

  .item-box:hover {
    box-shadow: 0 0 20px 0 rgba(64, 158, 255, 0.25);
  }

  .item-box.active {
    border: 1px solid rgb(64, 158, 255);
    box-shadow: inset 0 0 0 1px rgb(64, 158, 255);
  }
}
.view-box {
  .view-image {
    width: 100%;
    text-align: center;
  }

  .view-footer {
    :deep(.el-input-group__append) {
      padding: 0 10px;
    }
    .ac-icon {
      cursor: pointer;
    }
  }
}
.preview-box {
  width: 100%;
  height: 100%;
  overflow: auto;
  img {
    width: 100%;
    height: auto;
    display: block;
  }
}
</style>